<?php

namespace polymerize\auth\module\login;


use app\common\InstanceTrait;
use app\common\LoginType;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use app\model\UserToken;
use app\service\AliMobileService;

class AliGetMobile
{
    use InstanceTrait;

    /**
     * 阿里云一键登录
     * 三网通手机号码一键登录
     *
     * @param string $accessToken
     * @param string $ref
     * @return array
     */
    public function aliGetMobile(string $accessToken, string $ref): array
    {
        $ret = AliMobileService::instance()->GetMobile($accessToken);
        if ($ret['Code'] != 'OK') return ['code' => 400, 'msg' => $ret['Message']];
        $mobile = $ret['GetMobileResultDTO']['Mobile'];
        if (empty($mobile)) return ['code' => 400, 'msg' => '获取手机号码失败，请重试'];

        $where[] = ['mobile', '=', $mobile];
        $field   = 'id,mobile,status,create_time,avatar,login_type,ref';
        $user    = UserModel::where($where)->field($field)->find();
        if (empty($user)) {
            $user = UserModel::mobile_register($mobile, '*', $ref);
            if (!$user) return ['code' => 400, 'msg' => '注册失败，请重试'];
        }

        $userStatus = true;
        if ($user['status'] != 1) $userStatus = false;
        $param = [
            'uid'         => $user['id'],
            'type'        => 2,
            'user_status' => $userStatus ? 1 : 2,
            'status'      => $userStatus ? 1 : 2,
            'login_type'  => LoginType::LOGIN_TYPE_PHONE->value
        ];
        UserBehaviorLog::log($param);
        if (!$userStatus) return ['code' => 400, 'msg' => '当前账号状态异常，请联系管理员'];

        $token         = UserToken::loginToken($user, LoginType::LOGIN_TYPE_PHONE->value);
        $data['token'] = $token['token'] ?? '';
        return ['code' => 200, 'msg' => '', 'data' => $data];
    }
}
